package org.yh.leetcode;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author: yh
 * @Description:
 * @Date: Created in 15:26 2019/5/10
 * @Modified By:
 */
public class Test3 {

    public int romanToInt(String s) {
        //储存所有罗马数字
        Map<String, Integer> map = new HashMap<>();
        map.put("I", 1);
        map.put("V", 5);
        map.put("X", 10);
        map.put("L", 50);
        map.put("C", 100);
        map.put("D", 500);
        map.put("M", 1000);
        int sum = 0;
        for (int i = 0; i < s.length(); i++) {
            String s1 = Character.toString(s.charAt(i));
            Integer cur = map.get(s1);
            //判断这个字符是否是最后一个，避免空指针
            if (s.length() - 1 == i) {
                sum += cur;
                continue;
            }
            Integer next = map.get(Character.toString(s.charAt(i + 1)));
            //当前值如果小于下一个值，则获取罗马数字联合的值
            if (cur < next) {
                sum += next - cur;
                //这里由于是计算两个罗马符号的值，所以下一次循环跳过
                i++;
            } else {
                //正常情况 则 加上当前值
                sum += cur;
            }
        }
        return sum;
    }

    //阿拉伯数字转罗马数字
    public String intToRoman(int num) {
        int ints[] = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
        String roman[] = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < ints.length; i++) {
            while (ints[i] <= num) {
                sb.append(roman[i]);
                num -= ints[i];
            }
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        Test3 test3 = new Test3();
        //int sum = test3.romanToInt("MIX");
        //System.out.println("整数值为：" + sum);
        String s = test3.intToRoman(1022);
        System.out.println("罗马值为：" + s);
    }


}
